<template>
  <rt-view>
    <rt-header>
      <rt-navbar hide-back>
        <rt-search
          v-focus
          v-model="queryValue"
          :autoFocus = "true"
          placeholder="按文章名称进行查询"
          @on-search="searchContent"
        ></rt-search>
        <template slot="right">
          <rt-button type="sub" text @click="cancelClick">{{
            $_t('search.cancel', '取消')
          }}</rt-button>
        </template>
      </rt-navbar>
    </rt-header>
    <!-- 开启文章历史记录 -->
    <rt-content>
      <rt-search-history
        v-if= "show"
        :options="options"
        :model="model"
        @click="historyClick"
      />
      <!-- 展示文章的列表 -->
      <rt-list v-if= "!show" ref="articalList" :fetch="getDataList" @toggle="toggle">
        <div
          slot-scope="{ row }"
          class="list_content"
          @click="clickToDetail(row)"
        >
          <div class="desc">
            <div class="tille">{{ row.articName}}</div>
            <div class="footer">
              {{ row.openCount }} 阅读 . {{ row.commentCount }} 评论
            </div>
          </div>
          <div class="imgs">
            <!-- <img :src="imgUrl + row.imgUrl" /> -->
            <img :src="showRemotePic(row.imgUrl)" @error="showErrorPic($event)"/>
          </div>
        </div>
      </rt-list>
    </rt-content>
  </rt-view>
</template>

<script>
import { store, mapMutations } from 'vuex';
import { mapState } from 'vuex';
import rtSearchHistory from './searchArticleHistory';
export default {
  name: 'searchArticlen',
  components: {
    rtSearchHistory
  },
  filters: {
    nameStyle(value) {
      if (!value) return '';
      var count = 15;
      if (value.length > count) {
        return value.slice(0, count) + '...';
      }
      return value;
    }
  },
  data() {
    return {
      queryValue: '',
      show: true,
      // placeholder: '',
      count: 0,
      showHistory: true,
      options: JSON.parse(localStorage.getItem('article-history')) || [],
      // 搜索所用到的属性
      // imgUrl: process.env.HOST_URL + 'img/',
      tabs: 0,
      name: '',
      borderWidth: '8px',
      color: '#888',
      selectColor: '#53A4FC'
    };
  },
  computed: {
    ...mapState({
      placeholder: state => state.search.searchparams.placeholder,
      model: state => state.search.searchparams.entityName,
      entityNames: state => state.search.searchparams.entityNames,
      config: state => state.search.searchparams.config
    })
  },
  mounted() {
    this.options =
      JSON.parse(localStorage.getItem('article-history')) || [];
    this.$bus.$on('article-updated', this.onModelUpdated);
  },
  destroyed() {
    this.$bus.$off('article-updated', this.onModelUpdated);
  },
  methods: {
    ...mapMutations(['setSearchPageInfo', 'updateQueryValue']),
    onModelUpdated() {
      this.$refs.list.loadData();
    },
    historyClick(queryValue) {
      this.queryValue = queryValue;
      this.showHistory = false;
      this.queryList(queryValue);
    },
    searchContent(queryValue) {
      var patt = /^[\s]*$/;
      var pvalue = patt.test(queryValue);
      console.log(pvalue);
      this.queryValue = queryValue;
      // if(queryValue.indexOf(" ") < 0 && queryValue != null && queryValue != ''){
      if(!pvalue){
        //  1. 存储搜索历史
        this.saveToHistory(queryValue);
        //  2. 隐藏历史记录，显示查询列表    根据历史记录这个页面是否显示来解决了时而查询，浏览器报错的问题
        if(this.show){
          this.show = false;
        } else {
          this.$refs['articalList'].refreshData(1);
        }
      } else {
        this.show = true;
      }
    },
    saveToHistory(queryValue) {
      //  1. 存储搜索历史
      this.options.push(queryValue);
      this.options = this.options.filter((element, index, self) => {
        return self.indexOf(element) === index;
      });
      if (this.options.length > 10) {
        this.options.splice(0, 1);
      }
      localStorage.setItem(
        'article-history',
        JSON.stringify(this.options)
      );
    },
    queryList(queryValue) {
      this.show = false;
    },
    cancelClick() {
      this.$router.back();
    },

    // 文章列表展示
    getDataList(page) {
        const param = {
          pageIndex: page.pageIndex,
          pageSize: page.pageSize,
          name: this.queryValue
        };
        console.log(param);
        return new Promise(resolve => {
          rt.get(`/api/bbs/search/searchAllArticle`, param)
            .then(res => {
              // console.log(res);
              resolve(res);
            })
            .catch(error => {
              rt.showErrorToast(error);
            });
        });
    },
    toggle(showHeader) {
      this.showHeader = showHeader;
      this.$refs.content.resizeStyle();
    },
    clickToDetail(row) {
      this.$router.push({
            name: 'article-detail',
            query: { id: row.articId,
            name: row.articName }
          });
    },
    showRemotePic(name){
      return rt.showRemotePic(name);
    },
    showErrorPic(e){
      rt.showErrorPic(e);
    }
  }
};
</script>
<style lang="less" scoped>
.rt-navbar .rt-navbar-right .rt-btn-sub.is-text {
  color: #888;
}
// 文章搜索列表的样式
* {
  touch-action: none;
  touch-action: pan-y;
}
</style>
